package com.gollum.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSONObject;
import com.gollum.common.constant.SysConfigConstants;
import com.gollum.common.constant.SystemConstants;
import com.gollum.common.context.PageContextHolder;
import com.gollum.common.domain.response.TableSupport;
import com.gollum.common.enums.ConfigType;
import com.gollum.common.exception.BusinessException;
import com.gollum.common.exception.ServiceException;
import com.gollum.common.utils.BeanUtils;
import com.gollum.common.utils.StringUtils;
import com.gollum.common.utils.redis.RedisCache;
import com.gollum.jpa.common.PredicateBuilder;
import com.gollum.jpa.common.Specifications;
import com.gollum.jpa.domain.Page;
import com.gollum.jpa.domain.PageQueryRequest;
import com.gollum.jpa.service.JpaServerImpl;
import com.gollum.system.domain.dao.SysConfigDao;
import com.gollum.system.domain.model.SysConfig;
import com.gollum.system.domain.model.SysDictData;
import com.gollum.system.domain.model.SysLogininfor;
import com.gollum.system.domain.request.SysConfigRequest;
import com.gollum.system.domain.response.SysConfigResponse;
import com.gollum.system.domain.response.SysDictDataResponse;
import com.gollum.system.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 系统参数配置接口实现
 *
 * @author Herther
 * @version 1.0.0
 * @createTime 2022年09月04日 22:12:00
 */
@Service
public class SysConfigServiceImpl extends JpaServerImpl<SysConfig,Long> implements SysConfigService {

    @Autowired
    protected SysConfigDao sysConfigDao;

    @Autowired
    protected RedisCache redisCache;

    @Override
    public String getConfigValue(String keyName)
    {
        //获取redis key
        String key = getConfigKeyPrefix(keyName);
        String configValue = Convert.toStr(redisCache.getCacheObject(key));
        //如果没有找到的话就去查数据
        if (StringUtils.isBlank(configValue)) {
            SysConfig sysConfig = sysConfigDao.findByConfigKey(keyName);
            if (Objects.isNull(sysConfig))
            {
                throw new ServiceException("没有找到系统参数");
            }
            //放入到redis中
            redisCache.setCacheObject(key, sysConfig.getConfigValue());
            configValue = sysConfig.getConfigValue();
        }
        return configValue;
    }

    @Override
    public TableSupport<SysConfigResponse> listPage(SysConfigRequest params)
    {
        //获取分页参数以及排序规则
        Page<SysConfig> page
                = PageContextHolder.get().toPage();
        page = this.findAllWithPage(page,getParams(params));
        return TableSupport.toTableResponse(page, BeanUtils.copyToList(page.getRecords(), SysConfigResponse.class));
    }

    private Specification<SysConfig> getParams(SysConfigRequest params) {
        return Specifications.<SysConfig>and()
                    /** 参数ID */
                    .eq(Objects.nonNull(params.getId()),
                            SysConfig::getId,params.getId())
                    /** 参数名称 */
                    .like(StringUtils.isNotEmpty(params.getConfigName()),
                            SysConfig::getConfigName, params.getConfigName())
                    /** 参数键名 */
                    .eq(StringUtils.isNotEmpty(params.getConfigKey()),
                            SysConfig::getConfigKey, params.getConfigKey())
                    /** 参数键值 */
                    .eq(StringUtils.isNotEmpty(params.getConfigValue()),
                            SysConfig::getConfigValue, params.getConfigValue())
                    /** 系统内置（0是 1否） */
                    .eq(StringUtils.isNotEmpty(params.getConfigType()),
                            SysConfig::getConfigType, params.getConfigType())
                    /** 系统状态（0正常 1停用） */
                    .eq(StringUtils.isNotEmpty(params.getStatus()),
                            SysConfig::getStatus, params.getStatus())
                    /** 创建人 */
                    .eq(StringUtils.isNotEmpty(params.getCreateBy()),
                            SysConfig::getCreateBy, params.getCreateBy())
                    /**创建时间范围*/
                    .between(getBetweenCondition(params.getBeginTime()
                                    ,params.getEndTime())
                            , SysConfig::getCreateTime
                            , params.getBeginTime(),params.getEndTime())
                    .build();
    }


    /**
     * 添加系统参数前缀 合成key
     * @param
     * @return
     * @auther: Herther
     * @version 1.0.0
     * @date: 2022/9/4 22:20
     */
    public String getConfigKeyPrefix(String keyName){
        return new StringBuilder(SysConfigConstants.SYS_CONFIG_KEY).append(keyName).toString();
    }

    @Override
    public SysConfigResponse getDetailById(Long id) {
        SysConfig sysConfig = this.getById(id);
        if (Objects.isNull(sysConfig)){
            throw new BusinessException("查询不存在");
        }
        SysConfigResponse sysConfigResponse = new SysConfigResponse();
        BeanUtils.copyBeanProp(sysConfig, sysConfigResponse);
        return sysConfigResponse;
    }

    @Override
    public List<SysConfigResponse> getConfig(JSONObject jsonObject) {
        String type = jsonObject.get(SystemConstants.TYPE).toString();
        //如果为空则默认查询base参数
        if (StringUtils.isEmpty(type)){
            type = String.valueOf(ConfigType.BASE.ordinal());
        }
        Specification<SysConfig> params = Specifications.<SysConfig>and()
                .eq(SysConfig::getConfigType, type).build();
        List<SysConfig> sysConfigs = sysConfigDao.findAll(params);
        return BeanUtils.copyToList(sysConfigs, SysConfigResponse.class);
    }

}
